package com.oliver.picturebackendopenfign.manager.auth;


import com.oliver.picturebackendcommon.annotation.AuthCheck;
import com.oliver.picturebackendcommon.exception.BusinessException;
import com.oliver.picturebackendcommon.exception.ErrorCode;
import com.oliver.picturebackendcommon.model.enums.UserRoleEnum;
import com.oliver.picturebackendmodel.model.entity.User;
import com.oliver.picturebackendopenfign.feignClient.UserFeignClient;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName AuthInterceptor
 * @Description TODO
 * @Author snow
 * @Date 2024/12/10 21:17
 **/

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserFeignClient userFeignClient;


    @Around("@annotation(authCheck)")
    private Object doIntercept(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 获取当前登录用户
        User loginUser = userFeignClient.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //  不需要鉴权，直接放行
        if (mustRoleEnum == null){
            return joinPoint.proceed();
        }
        //  获取当前用户权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        //  如果当前用户没有权限，直接拒绝
        if (null == userRoleEnum){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //  如果必须要管理员权限，但是用户不是管理员权限，直接拒绝
        if(UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //  通过权限校验，放行
        return joinPoint.proceed();
    }

}
